package com.example.configuration;

import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryOrder",
        transactionManagerRef = "transactionManagerOrder",
        basePackages = {"com.example.order"}) //设置Repository所在位置
public class OrderConfig {

    @Resource(name = "dataSourceOrder")
    private DataSource dataSourceOrder;

    @Resource
    private JpaProperties jpaProperties;
    @Resource
    private HibernateProperties hibernateProperties;

    private Map<String, Object> getVendorProperties() {
        return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
    }

    @Bean(name = "entityManagerOrder")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryOrder(builder).getObject().createEntityManager();
    }

    @Bean(name = "entityManagerFactoryOrder")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryOrder(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(dataSourceOrder)
                .packages("com.example.order") //设置实体类所在位置
                .persistenceUnit("persistenceUnitOrder")
                .properties(getVendorProperties())
                .build();
    }

    @Bean(name = "transactionManagerOrder")
    PlatformTransactionManager transactionManagerOrder(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryOrder(builder).getObject());
    }

}